"""
核心数据库服务
Core Database Services

提供核心数据库功能的高级服务接口：
- WVP设备数据表操作
- 摄像头信息表操作
- AI分析结果表操作
- 用户和权限表操作
"""
import logging
from typing import List, Optional, Dict, Any, Tuple
from datetime import datetime, timedelta
import json
import hashlib

from .simple_db import get_database_manager, DatabaseManager
from .models import (
    Camera, WVPDevice, WVPChannel, AIResult, User, SystemConfig,
    CameraStatus, StreamStatus, UserRole, PageResult, OperationResult
)

logger = logging.getLogger(__name__)


class CameraService:
    """摄像头数据服务"""
    
    def __init__(self, db_manager: Optional[DatabaseManager] = None):
        self.db = db_manager or get_database_manager()
    
    def create_camera(self, camera: Camera) -> OperationResult:
        """创建摄像头"""
        try:
            # 检查名称是否已存在
            existing = self.get_camera_by_name(camera.name)
            if existing.success and existing.data:
                return OperationResult(
                    success=False,
                    message=f"摄像头名称 '{camera.name}' 已存在",
                    error_code="CAMERA_NAME_EXISTS"
                )
            
            camera_data = camera.to_dict()
            camera_data.pop('id', None)  # 移除ID，让数据库自动生成
            camera_data.pop('created_at', None)
            camera_data.pop('updated_at', None)
            
            camera_id = self.db.create_camera(camera_data)
            
            # 获取创建的摄像头
            created_camera = self.get_camera_by_id(camera_id)
            
            return OperationResult(
                success=True,
                message="摄像头创建成功",
                data=created_camera.data if created_camera.success else None
            )
            
        except Exception as e:
            logger.error(f"创建摄像头失败: {e}")
            return OperationResult(
                success=False,
                message=f"创建摄像头失败: {str(e)}",
                error_code="CAMERA_CREATE_ERROR"
            )
    
    def get_camera_by_id(self, camera_id: int) -> OperationResult:
        """根据ID获取摄像头"""
        try:
            camera_data = self.db.get_camera_by_id(camera_id)
            if camera_data:
                camera = Camera.from_dict(camera_data)
                return OperationResult(
                    success=True,
                    message="获取摄像头成功",
                    data=camera
                )
            else:
                return OperationResult(
                    success=False,
                    message="摄像头不存在",
                    error_code="CAMERA_NOT_FOUND"
                )
        except Exception as e:
            logger.error(f"获取摄像头失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取摄像头失败: {str(e)}",
                error_code="CAMERA_GET_ERROR"
            )
    
    def get_camera_by_name(self, name: str) -> OperationResult:
        """根据名称获取摄像头"""
        try:
            camera_data = self.db.get_camera_by_name(name)
            if camera_data:
                camera = Camera.from_dict(camera_data)
                return OperationResult(
                    success=True,
                    message="获取摄像头成功",
                    data=camera
                )
            else:
                return OperationResult(
                    success=False,
                    message="摄像头不存在",
                    error_code="CAMERA_NOT_FOUND"
                )
        except Exception as e:
            logger.error(f"获取摄像头失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取摄像头失败: {str(e)}",
                error_code="CAMERA_GET_ERROR"
            )
    
    def update_camera(self, camera_id: int, update_data: Dict[str, Any]) -> OperationResult:
        """更新摄像头信息"""
        try:
            # 检查摄像头是否存在
            existing = self.get_camera_by_id(camera_id)
            if not existing.success:
                return existing
            
            # 如果更新名称，检查是否重复
            if 'name' in update_data:
                name_check = self.get_camera_by_name(update_data['name'])
                if name_check.success and name_check.data.id != camera_id:
                    return OperationResult(
                        success=False,
                        message=f"摄像头名称 '{update_data['name']}' 已存在",
                        error_code="CAMERA_NAME_EXISTS"
                    )
            
            success = self.db.update_camera(camera_id, update_data)
            if success:
                # 获取更新后的摄像头
                updated_camera = self.get_camera_by_id(camera_id)
                return OperationResult(
                    success=True,
                    message="摄像头更新成功",
                    data=updated_camera.data if updated_camera.success else None
                )
            else:
                return OperationResult(
                    success=False,
                    message="摄像头更新失败",
                    error_code="CAMERA_UPDATE_ERROR"
                )
                
        except Exception as e:
            logger.error(f"更新摄像头失败: {e}")
            return OperationResult(
                success=False,
                message=f"更新摄像头失败: {str(e)}",
                error_code="CAMERA_UPDATE_ERROR"
            )
    
    def delete_camera(self, camera_id: int) -> OperationResult:
        """删除摄像头"""
        try:
            # 检查摄像头是否存在
            existing = self.get_camera_by_id(camera_id)
            if not existing.success:
                return existing
            
            success = self.db.delete_camera(camera_id)
            if success:
                return OperationResult(
                    success=True,
                    message="摄像头删除成功"
                )
            else:
                return OperationResult(
                    success=False,
                    message="摄像头删除失败",
                    error_code="CAMERA_DELETE_ERROR"
                )
                
        except Exception as e:
            logger.error(f"删除摄像头失败: {e}")
            return OperationResult(
                success=False,
                message=f"删除摄像头失败: {str(e)}",
                error_code="CAMERA_DELETE_ERROR"
            )
    
    def get_camera_list(self, filters: Dict[str, Any] = None, 
                       page: int = 1, size: int = 10) -> OperationResult:
        """获取摄像头列表"""
        try:
            cameras_data, total = self.db.get_camera_list(filters, page, size)
            
            cameras = [Camera.from_dict(data) for data in cameras_data]
            
            page_result = PageResult(
                items=cameras,
                total=total,
                page=page,
                size=size
            )
            
            return OperationResult(
                success=True,
                message="获取摄像头列表成功",
                data=page_result
            )
            
        except Exception as e:
            logger.error(f"获取摄像头列表失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取摄像头列表失败: {str(e)}",
                error_code="CAMERA_LIST_ERROR"
            )
    
    def get_cameras_by_status(self, status: str) -> OperationResult:
        """根据状态获取摄像头列表"""
        try:
            cameras_data = self.db.get_cameras_by_status(status)
            cameras = [Camera.from_dict(data) for data in cameras_data]
            
            return OperationResult(
                success=True,
                message="获取摄像头列表成功",
                data=cameras
            )
            
        except Exception as e:
            logger.error(f"获取摄像头列表失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取摄像头列表失败: {str(e)}",
                error_code="CAMERA_LIST_ERROR"
            )
    
    def get_ai_enabled_cameras(self, status_filter: Optional[str] = None) -> OperationResult:
        """获取启用AI的摄像头列表"""
        try:
            cameras_data = self.db.get_ai_enabled_cameras(status_filter)
            cameras = [Camera.from_dict(data) for data in cameras_data]
            
            return OperationResult(
                success=True,
                message="获取AI摄像头列表成功",
                data=cameras
            )
            
        except Exception as e:
            logger.error(f"获取AI摄像头列表失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取AI摄像头列表失败: {str(e)}",
                error_code="CAMERA_LIST_ERROR"
            )
    
    def batch_update_status(self, camera_ids: List[int], status: str) -> OperationResult:
        """批量更新摄像头状态"""
        try:
            if not camera_ids:
                return OperationResult(
                    success=False,
                    message="摄像头ID列表不能为空",
                    error_code="INVALID_PARAMS"
                )
            
            updated_count = self.db.batch_update_status(camera_ids, status)
            
            return OperationResult(
                success=True,
                message=f"成功更新 {updated_count} 个摄像头状态",
                data={"updated_count": updated_count}
            )
            
        except Exception as e:
            logger.error(f"批量更新摄像头状态失败: {e}")
            return OperationResult(
                success=False,
                message=f"批量更新摄像头状态失败: {str(e)}",
                error_code="CAMERA_BATCH_UPDATE_ERROR"
            )
    
    def get_statistics(self) -> OperationResult:
        """获取摄像头统计信息"""
        try:
            stats = self.db.get_statistics()
            
            return OperationResult(
                success=True,
                message="获取统计信息成功",
                data=stats
            )
            
        except Exception as e:
            logger.error(f"获取统计信息失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取统计信息失败: {str(e)}",
                error_code="CAMERA_STATS_ERROR"
            )

class WVPService:
    """WVP设备数据服务"""
    
    def __init__(self, db_manager: Optional[DatabaseManager] = None):
        self.db = db_manager or get_database_manager()
    
    def save_device(self, device_data: Dict[str, Any]) -> OperationResult:
        """保存WVP设备数据"""
        try:
            # 检查设备是否已存在
            existing_query = 'SELECT id FROM wvp_devices WHERE device_id = ?'
            existing = self.db.execute_query(existing_query, (device_data.get('device_id'),))
            
            if existing:
                # 更新现有设备
                update_query = '''
                    UPDATE wvp_devices SET 
                        device_name = ?, manufacturer = ?, model = ?, firmware = ?,
                        transport = ?, stream_mode = ?, ip = ?, port = ?,
                        host_address = ?, expires = ?, register_time = ?, keepalive_time = ?,
                        channel_count = ?, status = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE device_id = ?
                '''
                
                params = (
                    device_data.get('device_name'),
                    device_data.get('manufacturer'),
                    device_data.get('model'),
                    device_data.get('firmware'),
                    device_data.get('transport'),
                    device_data.get('stream_mode'),
                    device_data.get('ip'),
                    device_data.get('port'),
                    device_data.get('host_address'),
                    device_data.get('expires'),
                    device_data.get('register_time'),
                    device_data.get('keepalive_time'),
                    device_data.get('channel_count', 0),
                    device_data.get('status', 'online'),
                    device_data.get('device_id')
                )
                
                self.db.execute_update(update_query, params)
                device_id = existing[0]['id']
            else:
                # 插入新设备
                insert_query = '''
                    INSERT INTO wvp_devices (
                        device_id, device_name, manufacturer, model, firmware,
                        transport, stream_mode, ip, port, host_address, expires,
                        register_time, keepalive_time, channel_count, status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                '''
                
                params = (
                    device_data.get('device_id'),
                    device_data.get('device_name'),
                    device_data.get('manufacturer'),
                    device_data.get('model'),
                    device_data.get('firmware'),
                    device_data.get('transport'),
                    device_data.get('stream_mode'),
                    device_data.get('ip'),
                    device_data.get('port'),
                    device_data.get('host_address'),
                    device_data.get('expires'),
                    device_data.get('register_time'),
                    device_data.get('keepalive_time'),
                    device_data.get('channel_count', 0),
                    device_data.get('status', 'online')
                )
                
                device_id = self.db.execute_insert(insert_query, params)
            
            return OperationResult(
                success=True,
                message="WVP设备保存成功",
                data={"device_id": device_id}
            )
            
        except Exception as e:
            logger.error(f"保存WVP设备失败: {e}")
            return OperationResult(
                success=False,
                message=f"保存WVP设备失败: {str(e)}",
                error_code="WVP_DEVICE_SAVE_ERROR"
            )
    
    def save_channel(self, channel_data: Dict[str, Any]) -> OperationResult:
        """保存WVP通道数据"""
        try:
            # 检查通道是否已存在
            existing_query = 'SELECT id FROM wvp_channels WHERE device_id = ? AND channel_id = ?'
            existing = self.db.execute_query(existing_query, 
                                           (channel_data.get('device_id'), channel_data.get('channel_id')))
            
            if existing:
                # 更新现有通道
                update_query = '''
                    UPDATE wvp_channels SET 
                        channel_name = ?, manufacturer = ?, model = ?, owner = ?,
                        civil_code = ?, block = ?, address = ?, parental = ?,
                        parent_id = ?, safety_way = ?, register_way = ?, cert_num = ?,
                        certifiable = ?, err_code = ?, end_time = ?, secrecy = ?,
                        ip_address = ?, port = ?, password = ?, ptz_type = ?,
                        status = ?, longitude = ?, latitude = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE device_id = ? AND channel_id = ?
                '''
                
                params = (
                    channel_data.get('channel_name'),
                    channel_data.get('manufacturer'),
                    channel_data.get('model'),
                    channel_data.get('owner'),
                    channel_data.get('civil_code'),
                    channel_data.get('block'),
                    channel_data.get('address'),
                    channel_data.get('parental', 0),
                    channel_data.get('parent_id'),
                    channel_data.get('safety_way', 0),
                    channel_data.get('register_way', 1),
                    channel_data.get('cert_num'),
                    channel_data.get('certifiable', 0),
                    channel_data.get('err_code', 0),
                    channel_data.get('end_time'),
                    channel_data.get('secrecy'),
                    channel_data.get('ip_address'),
                    channel_data.get('port'),
                    channel_data.get('password'),
                    channel_data.get('ptz_type', 0),
                    channel_data.get('status', 'online'),
                    channel_data.get('longitude', 0.0),
                    channel_data.get('latitude', 0.0),
                    channel_data.get('device_id'),
                    channel_data.get('channel_id')
                )
                
                self.db.execute_update(update_query, params)
                channel_id = existing[0]['id']
            else:
                # 插入新通道
                insert_query = '''
                    INSERT INTO wvp_channels (
                        device_id, channel_id, channel_name, manufacturer, model, owner,
                        civil_code, block, address, parental, parent_id, safety_way,
                        register_way, cert_num, certifiable, err_code, end_time, secrecy,
                        ip_address, port, password, ptz_type, status, longitude, latitude
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                '''
                
                params = (
                    channel_data.get('device_id'),
                    channel_data.get('channel_id'),
                    channel_data.get('channel_name'),
                    channel_data.get('manufacturer'),
                    channel_data.get('model'),
                    channel_data.get('owner'),
                    channel_data.get('civil_code'),
                    channel_data.get('block'),
                    channel_data.get('address'),
                    channel_data.get('parental', 0),
                    channel_data.get('parent_id'),
                    channel_data.get('safety_way', 0),
                    channel_data.get('register_way', 1),
                    channel_data.get('cert_num'),
                    channel_data.get('certifiable', 0),
                    channel_data.get('err_code', 0),
                    channel_data.get('end_time'),
                    channel_data.get('secrecy'),
                    channel_data.get('ip_address'),
                    channel_data.get('port'),
                    channel_data.get('password'),
                    channel_data.get('ptz_type', 0),
                    channel_data.get('status', 'online'),
                    channel_data.get('longitude', 0.0),
                    channel_data.get('latitude', 0.0)
                )
                
                channel_id = self.db.execute_insert(insert_query, params)
            
            return OperationResult(
                success=True,
                message="WVP通道保存成功",
                data={"channel_id": channel_id}
            )
            
        except Exception as e:
            logger.error(f"保存WVP通道失败: {e}")
            return OperationResult(
                success=False,
                message=f"保存WVP通道失败: {str(e)}",
                error_code="WVP_CHANNEL_SAVE_ERROR"
            )
    
    def get_devices(self, status_filter: Optional[str] = None) -> OperationResult:
        """获取WVP设备列表"""
        try:
            if status_filter:
                query = 'SELECT * FROM wvp_devices WHERE status = ? ORDER BY device_name'
                params = (status_filter,)
            else:
                query = 'SELECT * FROM wvp_devices ORDER BY device_name'
                params = ()
            
            devices_data = self.db.execute_query(query, params)
            devices = [WVPDevice.from_dict(data) for data in devices_data]
            
            return OperationResult(
                success=True,
                message="获取WVP设备列表成功",
                data=devices
            )
            
        except Exception as e:
            logger.error(f"获取WVP设备列表失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取WVP设备列表失败: {str(e)}",
                error_code="WVP_DEVICE_LIST_ERROR"
            )
    
    def get_channels(self, device_id: Optional[str] = None) -> OperationResult:
        """获取WVP通道列表"""
        try:
            if device_id:
                query = 'SELECT * FROM wvp_channels WHERE device_id = ? ORDER BY channel_name'
                params = (device_id,)
            else:
                query = 'SELECT * FROM wvp_channels ORDER BY device_id, channel_name'
                params = ()
            
            channels_data = self.db.execute_query(query, params)
            channels = [WVPChannel.from_dict(data) for data in channels_data]
            
            return OperationResult(
                success=True,
                message="获取WVP通道列表成功",
                data=channels
            )
            
        except Exception as e:
            logger.error(f"获取WVP通道列表失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取WVP通道列表失败: {str(e)}",
                error_code="WVP_CHANNEL_LIST_ERROR"
            )


class AIResultService:
    """AI分析结果服务"""
    
    def __init__(self, db_manager: Optional[DatabaseManager] = None):
        self.db = db_manager or get_database_manager()
    
    def save_result(self, camera_id: int, algorithm: str, result_data: Dict[str, Any], 
                   confidence: float = None, processing_time: float = None) -> OperationResult:
        """保存AI分析结果"""
        try:
            result_id = self.db.save_ai_result(camera_id, algorithm, result_data, 
                                             confidence, processing_time)
            
            return OperationResult(
                success=True,
                message="AI结果保存成功",
                data={"result_id": result_id}
            )
            
        except Exception as e:
            logger.error(f"保存AI结果失败: {e}")
            return OperationResult(
                success=False,
                message=f"保存AI结果失败: {str(e)}",
                error_code="AI_RESULT_SAVE_ERROR"
            )
    
    def get_results(self, camera_id: int, algorithm: Optional[str] = None, 
                   limit: int = 100) -> OperationResult:
        """获取AI分析结果"""
        try:
            results_data = self.db.get_ai_results(camera_id, algorithm, limit)
            results = []
            
            for data in results_data:
                # 解析result_data字段
                try:
                    if isinstance(data['result_data'], str):
                        data['result_data'] = json.loads(data['result_data'])
                except:
                    pass
                
                results.append(AIResult(
                    id=data['id'],
                    camera_id=data['camera_id'],
                    algorithm=data['algorithm'],
                    result_data=data['result_data'],
                    confidence=data['confidence'],
                    processing_time=data['processing_time'],
                    created_at=datetime.fromisoformat(data['created_at']) if data['created_at'] else None
                ))
            
            return OperationResult(
                success=True,
                message="获取AI结果成功",
                data=results
            )
            
        except Exception as e:
            logger.error(f"获取AI结果失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取AI结果失败: {str(e)}",
                error_code="AI_RESULT_GET_ERROR"
            )
    
    def cleanup_old_results(self, days: int = 30) -> OperationResult:
        """清理旧的AI结果"""
        try:
            deleted_count = self.db.cleanup_old_ai_results(days)
            
            return OperationResult(
                success=True,
                message=f"清理了 {deleted_count} 条旧的AI结果",
                data={"deleted_count": deleted_count}
            )
            
        except Exception as e:
            logger.error(f"清理AI结果失败: {e}")
            return OperationResult(
                success=False,
                message=f"清理AI结果失败: {str(e)}",
                error_code="AI_RESULT_CLEANUP_ERROR"
            )


class UserService:
    """用户管理服务"""
    
    def __init__(self, db_manager: Optional[DatabaseManager] = None):
        self.db = db_manager or get_database_manager()
    
    def create_user(self, username: str, password: str, email: Optional[str] = None,
                   full_name: Optional[str] = None, role: str = "user") -> OperationResult:
        """创建用户"""
        try:
            # 检查用户名是否已存在
            existing_query = 'SELECT id FROM users WHERE username = ?'
            existing = self.db.execute_query(existing_query, (username,))
            
            if existing:
                return OperationResult(
                    success=False,
                    message=f"用户名 '{username}' 已存在",
                    error_code="USERNAME_EXISTS"
                )
            
            # 生成密码哈希
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            
            # 插入新用户
            insert_query = '''
                INSERT INTO users (username, password_hash, email, full_name, role)
                VALUES (?, ?, ?, ?, ?)
            '''
            
            params = (username, password_hash, email, full_name, role)
            user_id = self.db.execute_insert(insert_query, params)
            
            return OperationResult(
                success=True,
                message="用户创建成功",
                data={"user_id": user_id}
            )
            
        except Exception as e:
            logger.error(f"创建用户失败: {e}")
            return OperationResult(
                success=False,
                message=f"创建用户失败: {str(e)}",
                error_code="USER_CREATE_ERROR"
            )
    
    def authenticate_user(self, username: str, password: str) -> OperationResult:
        """用户认证"""
        try:
            # 获取用户信息
            query = 'SELECT * FROM users WHERE username = ? AND is_active = TRUE'
            user_data = self.db.execute_query(query, (username,))
            
            if not user_data:
                return OperationResult(
                    success=False,
                    message="用户名或密码错误",
                    error_code="AUTH_FAILED"
                )
            
            user_info = user_data[0]
            
            # 验证密码
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            if user_info['password_hash'] != password_hash:
                return OperationResult(
                    success=False,
                    message="用户名或密码错误",
                    error_code="AUTH_FAILED"
                )
            
            # 更新最后登录时间
            update_query = 'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?'
            self.db.execute_update(update_query, (user_info['id'],))
            
            # 创建用户对象（不包含密码）
            user = User(
                id=user_info['id'],
                username=user_info['username'],
                email=user_info['email'],
                full_name=user_info['full_name'],
                role=UserRole(user_info['role']),
                is_active=user_info['is_active'],
                created_at=datetime.fromisoformat(user_info['created_at']) if user_info['created_at'] else None,
                updated_at=datetime.fromisoformat(user_info['updated_at']) if user_info['updated_at'] else None,
                last_login=datetime.now()
            )
            
            return OperationResult(
                success=True,
                message="认证成功",
                data=user
            )
            
        except Exception as e:
            logger.error(f"用户认证失败: {e}")
            return OperationResult(
                success=False,
                message=f"用户认证失败: {str(e)}",
                error_code="AUTH_ERROR"
            )
    
    def get_user_by_id(self, user_id: int) -> OperationResult:
        """根据ID获取用户"""
        try:
            query = 'SELECT * FROM users WHERE id = ?'
            user_data = self.db.execute_query(query, (user_id,))
            
            if not user_data:
                return OperationResult(
                    success=False,
                    message="用户不存在",
                    error_code="USER_NOT_FOUND"
                )
            
            user_info = user_data[0]
            user = User(
                id=user_info['id'],
                username=user_info['username'],
                email=user_info['email'],
                full_name=user_info['full_name'],
                role=UserRole(user_info['role']),
                is_active=user_info['is_active'],
                created_at=datetime.fromisoformat(user_info['created_at']) if user_info['created_at'] else None,
                updated_at=datetime.fromisoformat(user_info['updated_at']) if user_info['updated_at'] else None,
                last_login=datetime.fromisoformat(user_info['last_login']) if user_info['last_login'] else None
            )
            
            return OperationResult(
                success=True,
                message="获取用户成功",
                data=user
            )
            
        except Exception as e:
            logger.error(f"获取用户失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取用户失败: {str(e)}",
                error_code="USER_GET_ERROR"
            )


class SystemConfigService:
    """系统配置服务"""
    
    def __init__(self, db_manager: Optional[DatabaseManager] = None):
        self.db = db_manager or get_database_manager()
    
    def set_config(self, key: str, value: Any, config_type: str = "string", 
                  description: Optional[str] = None) -> OperationResult:
        """设置系统配置"""
        try:
            # 转换值为字符串
            if isinstance(value, (dict, list)):
                value_str = json.dumps(value)
                config_type = "json"
            elif isinstance(value, bool):
                value_str = str(value).lower()
                config_type = "bool"
            elif isinstance(value, (int, float)):
                value_str = str(value)
                config_type = "int" if isinstance(value, int) else "float"
            else:
                value_str = str(value)
            
            # 检查配置是否已存在
            existing_query = 'SELECT id FROM system_config WHERE config_key = ?'
            existing = self.db.execute_query(existing_query, (key,))
            
            if existing:
                # 更新现有配置
                update_query = '''
                    UPDATE system_config SET 
                        config_value = ?, config_type = ?, description = ?, 
                        updated_at = CURRENT_TIMESTAMP
                    WHERE config_key = ?
                '''
                params = (value_str, config_type, description, key)
                self.db.execute_update(update_query, params)
            else:
                # 插入新配置
                insert_query = '''
                    INSERT INTO system_config (config_key, config_value, config_type, description)
                    VALUES (?, ?, ?, ?)
                '''
                params = (key, value_str, config_type, description)
                self.db.execute_insert(insert_query, params)
            
            return OperationResult(
                success=True,
                message="配置设置成功"
            )
            
        except Exception as e:
            logger.error(f"设置配置失败: {e}")
            return OperationResult(
                success=False,
                message=f"设置配置失败: {str(e)}",
                error_code="CONFIG_SET_ERROR"
            )
    
    def get_config(self, key: str) -> OperationResult:
        """获取系统配置"""
        try:
            query = 'SELECT * FROM system_config WHERE config_key = ?'
            config_data = self.db.execute_query(query, (key,))
            
            if not config_data:
                return OperationResult(
                    success=False,
                    message=f"配置 '{key}' 不存在",
                    error_code="CONFIG_NOT_FOUND"
                )
            
            config_info = config_data[0]
            config = SystemConfig(
                id=config_info['id'],
                config_key=config_info['config_key'],
                config_value=config_info['config_value'],
                config_type=config_info['config_type'],
                description=config_info['description'],
                created_at=datetime.fromisoformat(config_info['created_at']) if config_info['created_at'] else None,
                updated_at=datetime.fromisoformat(config_info['updated_at']) if config_info['updated_at'] else None
            )
            
            return OperationResult(
                success=True,
                message="获取配置成功",
                data=config
            )
            
        except Exception as e:
            logger.error(f"获取配置失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取配置失败: {str(e)}",
                error_code="CONFIG_GET_ERROR"
            )
    
    def get_all_configs(self) -> OperationResult:
        """获取所有系统配置"""
        try:
            query = 'SELECT * FROM system_config ORDER BY config_key'
            configs_data = self.db.execute_query(query)
            
            configs = []
            for config_info in configs_data:
                config = SystemConfig(
                    id=config_info['id'],
                    config_key=config_info['config_key'],
                    config_value=config_info['config_value'],
                    config_type=config_info['config_type'],
                    description=config_info['description'],
                    created_at=datetime.fromisoformat(config_info['created_at']) if config_info['created_at'] else None,
                    updated_at=datetime.fromisoformat(config_info['updated_at']) if config_info['updated_at'] else None
                )
                configs.append(config)
            
            return OperationResult(
                success=True,
                message="获取所有配置成功",
                data=configs
            )
            
        except Exception as e:
            logger.error(f"获取所有配置失败: {e}")
            return OperationResult(
                success=False,
                message=f"获取所有配置失败: {str(e)}",
                error_code="CONFIG_LIST_ERROR"
            )


# 全局服务实例
_camera_service: Optional[CameraService] = None
_wvp_service: Optional[WVPService] = None
_ai_result_service: Optional[AIResultService] = None
_user_service: Optional[UserService] = None
_system_config_service: Optional[SystemConfigService] = None


def get_camera_service() -> CameraService:
    """获取摄像头服务实例"""
    global _camera_service
    if _camera_service is None:
        _camera_service = CameraService()
    return _camera_service


def get_wvp_service() -> WVPService:
    """获取WVP服务实例"""
    global _wvp_service
    if _wvp_service is None:
        _wvp_service = WVPService()
    return _wvp_service


def get_ai_result_service() -> AIResultService:
    """获取AI结果服务实例"""
    global _ai_result_service
    if _ai_result_service is None:
        _ai_result_service = AIResultService()
    return _ai_result_service


def get_user_service() -> UserService:
    """获取用户服务实例"""
    global _user_service
    if _user_service is None:
        _user_service = UserService()
    return _user_service


def get_system_config_service() -> SystemConfigService:
    """获取系统配置服务实例"""
    global _system_config_service
    if _system_config_service is None:
        _system_config_service = SystemConfigService()
    return _system_config_service